package com.jgads.ad.sdk.mediation.adapter;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.reward.MediationCustomRewardVideoLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationRewardItem;
import com.jgads.ad.sdk.mediation.utils.ThreadUtils;
import com.junion.ad.BidLossNotice;
import com.junion.ad.RewardAd;
import com.junion.ad.bean.RewardAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.RewardAdListener;

import java.util.Map;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 12/23/21 6:09 PM
 */
public class CustomerRewardAdapter extends MediationCustomRewardVideoLoader {

    private RewardAd rewardAd;
    private RewardAdInfo rewardAdInfo;

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {

        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                rewardAd = new RewardAd(context);
                rewardAd.setListener(new RewardAdListener() {

                    @Override
                    public void onAdReceive(RewardAdInfo adInfo) {
                        rewardAdInfo = adInfo;

                        if (isClientBidding() && adInfo != null) {//bidding广告类型
                            //bidding广告成功回调，回传竞价广告价格 单位：分
                            callLoadSuccess(adInfo.getBidPrice());
                        } else {
                            //普通广告成功回调
                            callLoadSuccess();
                        }
                    }

                    @Override
                    public void onAdReward(RewardAdInfo adInfo) {
                        callRewardVideoRewardVerify(new MediationRewardItem() {
                            @Override
                            public boolean rewardVerify() {
                                return true;
                            }

                            @Override
                            public float getAmount() {
                                return 0;
                            }

                            @Override
                            public String getRewardName() {
                                return null;
                            }

                            @Override
                            public Map<String, Object> getCustomData() {
                                return null;
                            }
                        });
                    }

                    @Override
                    public void onAdExpose(RewardAdInfo adInfo) {
                        callRewardVideoAdShow();
                    }

                    @Override
                    public void onAdClick(RewardAdInfo adInfo) {
                        callRewardVideoAdClick();
                    }

                    @Override
                    public void onAdClose(RewardAdInfo adInfo) {
                        callRewardVideoAdClosed();
                    }

                    @Override
                    public void onVideoCompleted(RewardAdInfo adInfo) {
                        callRewardVideoComplete();
                    }

                    @Override
                    public void onVideoSkip(RewardAdInfo adInfo) {
                    }

                    @Override
                    public void onVideoError(RewardAdInfo adInfo, String msg) {
                        callRewardVideoError();
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        callLoadFail(error.getCode(), error.getError());
                    }

                });

                if (serviceConfig != null) {
                    rewardAd.loadAd(serviceConfig.getADNNetworkSlotId());
                }
            }
        });
    }

    @Override
    public void showAd(final Activity activity) {
        Log.i(Const.TAG, "showAd "+ Thread.currentThread().toString());
        if (rewardAdInfo != null && activity != null && !activity.isFinishing()) {
            if (isClientBidding() && !rewardAdInfo.isReportBidWin()) {
                rewardAdInfo.sendWinNotice(rewardAdInfo.getBidPrice());
            }
            rewardAdInfo.showRewardAd(activity);
        }
    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        if (rewardAdInfo != null && !rewardAdInfo.isOvertime()) {
            return MediationConstant.AdIsReadyStatus.AD_IS_READY;
        } else {
            if (rewardAdInfo != null && rewardAdInfo.isOvertime()) {
                return MediationConstant.AdIsReadyStatus.AD_IS_EXPIRED; // 注意这里是AD_IS_EXPIRED
            }
            return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rewardAd != null) {
            rewardAd.release();
            rewardAd = null;
        }
        if (rewardAdInfo != null) {
            rewardAdInfo.release();
            rewardAdInfo = null;
        }
    }

    /**
     * @param win         是否在本次竞价中获胜
     * @param winnerPrice 获胜者价格，可能为0 ,如果没有胜出则该值是-1
     * @param loseReason  竞价失败原因 1:价格较低 2：广告返回超时 10001：其他；如果胜出则该值是-1
     * @param extra       扩展参数
     */
    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        Log.i(Const.TAG, "receiveBidResult   win = "+ win+"  "+
                "winnerPrice = "+winnerPrice +"  "+
                "loseReason = " +loseReason  +"  "+
                Thread.currentThread().toString());
        if (win) {
            //竞价成功
            if (rewardAdInfo != null && !rewardAdInfo.isReportBidWin()) {
                rewardAdInfo.sendWinNotice((int) winnerPrice);
            }
        } else {
            //竞价失败
            if (rewardAdInfo != null) {
                if (loseReason == 1) {
                    rewardAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.LOW_PRICE);
                } else {
                    rewardAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.OTHER);
                }
            }
        }
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

}
